$(document).ready(function(){
	$('#datebox').bind('datebox', function(e, passed){
		if (passed.method === "set") {
			$.mobile.changePage('#result');
			$('#simple-result').html('');
			var splited = passed.value.split('/');
			var day = splited[0];
			var month = splited[1];
			var year = splited[2];
			var url = "http://api.tamlinh.vn/lichVanSu/xemNgay/xem/ngay/" + day + "/thang/" 
			+ month + "/nam/" + year + "/key/tvi1102";
			$.ajax({
				url: url,
				dataType: "xml",
				error: function(e, txt, txt1) {
					alert(txt + "; " + txt1);
				},
				success: function(data) {
					$(data).find('item').each(function(){
						var name = $(this).find('name').text();
						var value = $(this).find('value').text();
						switch (name) {
						case "giohoangdao": {
							var pElem = $("<p>" + value + "</p>");	
							$('#simple-result').prepend(pElem);
							var bElem = $("<p><b>Giá»� tá»‘t</b></p>");
							$('#simple-result').prepend(bElem);
							break;
						}
						case "totdoivoi": {
							if (value != "") {
								var bElem = $("<p><b>NÃªn lÃ m</b></p>");
								$('#simple-result').append(bElem);
								$('#simple-result').append("<ul id='nenlam'></ul>");
								var substr = value.split('/ ');
								for (var i = 0; i < substr.length; i++) {
									$('#nenlam').append("<li>" + substr[i] + "</li>");
								}
							}
							break;
						}
						case "khongnenlam": {
							if (value != "") {
								var bElem = $("<p><b>KhÃ´ng nÃªn lÃ m</b></p>");
								$('#simple-result').append(bElem);
								$('#simple-result').append("<ul id='khongnenlam'></ul>");
								var substr = value.split('/ ');
								for (var i = 0; i < substr.length; i++) {
									$('#khongnenlam').append("<li>" + substr[i] + "</li>");
								}
							}
							break;
						}
						default:
							break;
						}
					});
				}
			});
		}
	});
	$('#xem-ket-qua').click(function(){
		var thang = $('#thang').val();
		var nam = $('#nam').val();
		var suKienId = $('#sukien').val();
		var url = "http://api.tamlinh.vn/lichvansu/chonngaytot/danhsachngaysukien/thangxem/"
				+ thang + "/namxem/" + nam + "/key/tvi1102/sukienid/" + suKienId;
		var dateArray = [];
		$.ajax({
			url: url,
			dataType: "xml",
			error: function(e, txt, txt1) {
				alert(txt + "; " + txt1);
			},
			success: function(data) {
				$(data).find('item').each(function(){
					var time = $(this).text().split(' ');
					var date = time[1];
					dateArray.push(date);
				});
				$('#datebox').datebox("option", {
					highDatesAlt: dateArray
				});
				var displayDate = new Date();
				displayDate.setFullYear(nam, thang - 1, 1);
				$('#datebox').datebox('setTheDate', displayDate);
			}
		});
	});
});
